import axios from 'axios';
import { stringify } from 'qs';
import { showNotify } from 'vant';

const SUCCESS_CODE = '0000';

const service = axios.create({
  timeout: 60000
});

service.defaults.withCredentials = true; // 让ajax携带cookie
service.interceptors.request.use(
  // 每次请求都自动携带Cookie
  (config) => {
    if (config.isPostform) {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
      config.data = stringify(config.data);
    }
    config.headers.token = window.localStorage.getItem('token') || '';
    config.headers.platform = 'h5';
    return config;
  },
  // eslint-disable-next-line handle-callback-err
  (error) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (rsp) => {
    if (rsp.data && rsp.data.code === SUCCESS_CODE) {
      return rsp.data;
    } else {
      return Promise.reject(rsp.data);
    }
  },
  // 拦截异常的响应
  (err) => {
    console.log('请求', err);
    switch (err.response.status) {
      case 401:
        showNotify({ type: 'danger', message: '登录已过期，请重新登录' });
        break;
      case 403:
        break;
      case 500:
        break;
      case 404:
        break;
      default:
        return Promise.reject(err);
    }
    return Promise.reject(err);
  }
);

//get封装
const get = (url, params = {}) => {
  return service({
    url,
    method: 'get',
    params
  });
};

const post = (url, data) => {
  return service({
    url,
    method: 'post',
    data
  });
};

const postForm = (url, data) => {
  return service({
    url,
    method: 'post',
    isPostform: true,
    data
  });
};

export default {
  service,
  get,
  post,
  postForm
};

// export default service;
